<template>
  <customContainer ref="customContainerRef" :config="config" />
  <!-- 新增-修改发货人信息弹出框 -->
  <el-dialog
    v-model="open"
    :title="title"
    :close-on-click-modal="false"
    append-to-body
  >
    <el-form
      ref="editform"
      inline
      label-width="160px"
      :rules="rules"
      :model="form"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name" :label-position="labelPosition">
            <el-input v-model="form.name" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公司名称" prop="corporateName" :label-position="labelPosition">
            <el-input v-model="form.corporateName" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="国家" prop="countryName" :label-position="labelPosition">
            <el-select 
              v-model="form.countryName"
              clearable
              placeholder="请选择国家"
              style="width: 100%;"
            >
              <el-option
                v-for="dict in dicts[DictDirection.国家]"
                :key="dict.id"
                :label="dict.countryChName"
                :value="dict.countryChName"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮编" prop="postcode" :label-position="labelPosition">
            <el-input v-model.trim="form.postcode" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="省/州" prop="provinceStateCode" :label-position="labelPosition">
            <el-input v-model="form.provinceStateCode" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="城市" prop="cityName" :label-position="labelPosition">
            <el-input
              v-model="form.cityName"
              clearable
              @blur="form.cityName = form.cityName.toString().trim()"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="电话" prop="telephone" :label-position="labelPosition">
            <el-input v-model.trim="form.telephone" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="地址1" prop="address1" :label-position="labelPosition">
            <el-input v-model="form.address1" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="地址2" prop="address2" :label-position="labelPosition">
        <el-input v-model="form.address2" clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div>
        <el-button type="primary" @click="submitServiceForm">确定</el-button>
        <el-button @click="cancelService">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import {
  Delete,
  Plus,
  Edit,
} from '@element-plus/icons-vue'
import { ref, getCurrentInstance, computed, defineProps } from 'vue'
import { ElMessage, ElMessageBox, ElButton } from 'element-plus'
import userDicts, { DictDirection } from '@/store/modules/dicts'
import { getAddress, editAddress, addAddress, delAddress, getAddressDetails } from '@/api/BusinessConfig/serviceChannel'

const props = defineProps({
  // eslint-disable-next-line vue/require-default-prop
  productId: {
    type: Number,
  },
  fatherOpen: {
    type: Boolean,
  },
})
const dicts = userDicts()
dicts.setDicts(DictDirection.国家) 
let // 查询参数
  queryParams = ref({
    pageSize: 10,
    pageNum: 1,
    id: undefined,
  }),
  // 选中数组
  ids = [],
  // 非单个禁用
  single = ref(true),
  // 非多个禁用
  multiple = ref(true),
  customContainerRef = ref(null),
  // 新增-修改弹出框
  open = ref(false),
  // 新增-修改标题
  title = ref(undefined),
  labelPosition = ref('right'),
  // 规则
  rules = {
    name: [{ required: true, message: '姓名未输入', trigger: 'blur' }],
    corporateName: [
      {
        required: true,
        message: '公司名称未输入',
        trigger: ['blur'],
      },
    ],
    serviceChannelCode: [
      {
        required: true,
        message: '服务商渠道名称未输入',
        trigger: ['blur', 'change'],
      },
    ],
    countryName: [
      {
        required: true,
        message: '国家名称未输入',
        trigger: ['blur', 'change'],
      },
    ],
    postcode: [{ required: true, message: '邮编未输入', trigger: 'blur' }],
    provinceStateCode: [{ required: true, message: '省/州未输入', trigger: 'blur' }],
    cityName: [{ required: true, message: '城市未输入', trigger: 'blur' }],
    telephone: [{ required: true, message: '电话未输入', trigger: 'blur' }],
    address1: [{ required: true, message: '地址 1 未输入', trigger: 'blur' }],
  },
  form = ref({
    id: undefined,
    name: undefined,
    corporateName: undefined,
    countryName: undefined,
    postcode: undefined,
    provinceStateCode: undefined,
    cityName: undefined,
    telephone: undefined,
    address1: undefined,
    address2: undefined,
    serviceChannelCode: undefined,
  }),
  editform = ref(null),
  {
    proxy,

  }:{
    proxy:any
 
  } = getCurrentInstance()
// 查询
const handleQuery = () => {
  customContainerRef.value.getList()
}
// 多选框选中数据
const handleSelectionChange = (rows: { [key: string]: any }[]) => {
  const rowsList = JSON.parse(JSON.stringify(rows))
  ids = rowsList.map((item) => item.id)
  single.value = rowsList.length != 1
  multiple.value = !rowsList.length
}
/** 新增按钮操作 */
const handleAdd = () => {
  console.log('1')
  open.value = true
  // title.value = '新增发件人'
}
// 重置新增修改表单
const reset = () => {
  form.value = {
    id: undefined,
    name: undefined,
    corporateName: undefined,
    countryName: undefined,
    postcode: undefined,
    provinceStateCode: undefined,
    cityName: undefined,
    telephone: undefined,
    address1: undefined,
    address2: undefined,
    serviceChannelCode: undefined,
  }
  proxy.$resetForm(editform.value)
}
// 确定新增-修改服务渠道
const submitServiceForm = () => {
  proxy.$validateForm(editform.value, async () => {
    form.value.serviceChannelCode = props.productId
    console.log(form.value.serviceChannelCode)
    if (form.value.id != undefined) {
      editAddress(form.value).then(res => {
        if (res.code == 200) {
          ElMessage.success('修改成功')
          handleQuery()
          reset()
          open.value = false
        }
      })
    } else {
      addAddress(form.value).then(res => {
        if (res.code == 200) {
          ElMessage.success('修改成功')
          handleQuery()
          reset()
          open.value = false
        }
      })
    }  
  })
}
// 取消新增-修改发件人
const cancelService = () => {
  reset()
  open.value = false
}
// 修改发件人
const handleUpdate = (row:{[key:string]:any}) => {
  const id = (row && row.id) || ids[0]
  getAddressDetails(id).then(res => {
    if (res.code == 200) {
      form.value = res.data
      open.value = true
      title.value = '修改发件人'
    }
  })
}
/** 删除按钮操作 */
const handleDelete = (row: { [key: string]: any }) => {
  const id = row.id || ids
  ElMessageBox.confirm(
    `"是否确认删除发货人编号为"${ id }"的数据项?"`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
  .then(() => delAddress(id))
  .then((res) => {
    if (res.code === 200) {
      handleQuery()
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(res.msg)
    }
  })
  .catch((error) => {
    if (error == 'cancel') {
      ElMessage.error(error)
    }
  })
}
const config = computed(() => ({
  query: {
    fields: [],
    queryParams: queryParams.value,
  },
  btns: [
    {
      title: '新增',
      icon: Plus,
      onClick: handleAdd,
    },
    {
      title: '编辑',
      icon: Edit,
      disabled: single.value,
      onClick: handleUpdate,
      type: 'success',
    },
    {
      title: '删除',
      icon: Delete,
      onClick: handleDelete,
      type: 'danger',
    },
  ],
  table: {
    columns: [
      { type: 'selection', width: '55', align: 'center' },
      {
        label: '编号',
        prop: 'id',
        align: 'center',
        width: '90',
      },
      {
        label: '姓名',
        prop: 'name',
        align: 'center',
        width: '90',
      },
      {
        label: '公司',
        prop: 'corporateName',
        align: 'center',
        width: '90',
      },
      {
        label: '国家',
        prop: 'countryName',
        align: 'center',
        width: '90',
        formatter: (row) => dicts.getDictLabel({ dict: DictDirection.国家, value: row.countryName }),
      },
      {
        label: '邮编',
        prop: 'postcode',
        align: 'center',
        width: '90',
      },
      {
        label: '详细地址1',
        prop: 'address1',
        align: 'center',
        width: '90',    
      },
      {
        label: '详细地址2',
        prop: 'address2',
        align: 'center',
        width: '90',
      },
      {
        label: '省州',
        prop: 'provinceStateCode',
        align: 'center',
        width: '90',
      },
      {
        label: '城市',
        prop: 'cityName',
        align: 'center',
        width: '90',
      },
      {
        label: '电话',
        prop: 'telephone',
        align: 'center',
        width: '90',
      },
      {
        label: '操作',
        align: 'center',
        showOverflowTooltip: false,
        className: 'custormFixedCol',
        width: '200',
        render: (h, params) => {
          const buttons = [
            {
              title: '编辑',
              icon: Edit,
              clickFun: handleUpdate,
            },
            {
              title: '删除',
              icon: Delete,
              clickFun: handleDelete,
             
            },
          ]
          return buttons.map((el) => h(
            ElButton,
            {
              text: true,
              type: 'primary',
              icon: el.icon,
              onClick: () => {
                el.clickFun(params.row)
              },
            },
            {
              default: () => el.title,
            },
          ))
        },
      },
    ],
    event: {
      onSelectionChange: (rows) => {
        handleSelectionChange(rows)
      },
    },
  },
  api: getAddress,
  requestTrans: (q) => {
    q.id = props.productId
    queryParams.value = q
    return q
  },
}))

</script>
